﻿using System.Collections.Generic;
using System.Linq;

namespace Restful.Net
{
    public class ContentTypeNegotiator
    {
        public Accept GetRequestedContentType(string[] acceptHeader)
        {
            if (acceptHeader == null || acceptHeader.Length == 0)
            {
                return null;
            }

            if (acceptHeader.Length == 1)
            {
                return new Accept(acceptHeader[0], true);
            }

            return ConvertToAccept(acceptHeader).OrderByDescending(ac => ac.Quality).First();
        }

        public IList<Accept> GetOrderedList(string[] acceptHeader)
        {
            if (acceptHeader == null || acceptHeader.Length == 0)
            {
                return new List<Accept>();
            }
            return ConvertToAccept(acceptHeader).OrderByDescending(ac => ac.Quality).ToList();
        }

        private IEnumerable<Accept> ConvertToAccept(string[] acceptHeader)
        {
            List<Accept> accepts = new List<Accept> { new Accept(acceptHeader.First(), true) };

            accepts.AddRange(acceptHeader.Skip(1).Select(ch => new Accept(ch)));

            return accepts;
        }

    }
}
